package cn.tedu.websocket;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


@Slf4j
@Component
@ServerEndpoint("/socket/{userId}")
public class WebSocketServer {
    public WebSocketServer(){
        System.out.println("WebSocketServer()创建了");
    }
    /**建立链接时执行
     * 参数中{userId}为WebSocketServer类上定义的userId
     * session 代表客户端与服务端的连接会话
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userid, Session session) {
           System.out.println("用户" + userid + "连接成功");
           //向客户端写消息(这里还可以通过一个定时任务，定时写)
           sendMsgToClient(session);
    }
    /**此方法在收到客户端消息时执行*/
    @OnMessage
    public void onMessage(String message,Session session) {
        log.info("收到来自客户端{}窗口的信息: {}",session.getId(),message);
        //在这里也可以通过session向客户端发消息
        sendMsgToClient(session);
    }

    private void sendMsgToClient(Session session) {
        try {
               session.getBasicRemote().sendText("server say：hello client " + System.currentTimeMillis());
        }catch (IOException e){
               e.printStackTrace();
        }
    }

    /**连接断开时执行*/
    @OnClose
    public void onClose(Session session){
        log.info("{} 连接断开了",session.getId());

    }
    /**连接通讯出错时执行*/
    @OnError
    public void onError(Session session,Throwable error){
        log.error("{}发生错误{}",session.getId(),error.getMessage());

    }
}
